package subject1.movieRentingSystem;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

class MovieRentingSystem {
    class MovieInfo {
        Integer shopId;
        Integer movieId;
        Integer price;
        Boolean rented;

        public MovieInfo(Integer shopId, Integer movieId, Integer price, Boolean rented) {
            this.shopId = shopId;
            this.movieId = movieId;
            this.price = price;
            this.rented = rented;
        }
    }

    // key -> shopId, value -> shopInfo
    Map<Integer, List<MovieInfo>> map1 = new HashMap<>();
    // key -> movieId, value -> shopIds
    Map<Integer, List<Integer>> map2 = new HashMap<>();

    // key -> movieId, value ->
    List<MovieInfo> movieInfos = new ArrayList<>();
    public MovieRentingSystem(int n, int[][] entries) {
        for (int[] entry : entries) {
            movieInfos.add(new MovieInfo(entry[0], entry[1], entry[2], false));
        }
    }
    
    public List<Integer> search(int movie) {
        return map2.get(movie);
    }
    
    public void rent(int shop, int movie) {
        setShopMoiveRentStatus(shop, movie, true);
    }
    
    public void drop(int shop, int movie) {
        setShopMoiveRentStatus(shop, movie, false);
    }

    private void setShopMoiveRentStatus(int shop, int movie, boolean rentStatus) {
        List<MovieInfo> movieInfos = map1.get(shop);
        for (MovieInfo movieInfo : movieInfos) {
            if (movieInfo.movieId == movie) {
                movieInfo.rented = rentStatus;
            }
        }
    }
    
    public List<List<Integer>> report() {
        return movieInfos.stream().filter(movieInfo -> movieInfo.rented).sorted(((o1, o2) -> o1.price == o2.price ? o1.shopId == o1.shopId ? o1.movieId - o2.movieId : o1.shopId - o2.shopId : o1.price - o2.price)).limit(5).map(movieInfo -> Arrays.asList(movieInfo.shopId, movieInfo.movieId)).collect(Collectors.toList());
    }
}

/**
 * Your MovieRentingSystem object will be instantiated and called as such:
 * MovieRentingSystem obj = new MovieRentingSystem(n, entries);
 * List<Integer> param_1 = obj.search(movie);
 * obj.rent(shop,movie);
 * obj.drop(shop,movie);
 * List<List<Integer>> param_4 = obj.report();
 */